package com.ivan.toolkit.swing;

import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

import lombok.Getter;
import lombok.Setter;

public class ImagePanel extends JPanel {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -2405169372835909886L;
	
	public static enum ImageType {
		LeftTop,
		RightBottom,
		Scaled,
		Render
	}
	
	Image image = null;
	
	@Setter @Getter
	ImageType style = ImageType.Scaled;
	
	@Setter @Getter
	boolean ownerDraw = true;

	/**
	 * Create the panel.
	 */
	public ImagePanel() {

	}
	
	public void setImage(Image image) {
		this.image = image;
		//this.invalidate();
		//this.repaint();
	}
	
	public static Image getImage(String image) {
		return new ImageIcon(ImagePanel.class.getResource(image)).getImage();
	}
	
	public void loadImage(String image) {
		this.image = getImage(image);
		this.invalidate();
		this.repaint();
	}

	protected void paintImage(Graphics g) {
		
		if(image == null) {
			//System.err.println("ImagePanel: image not loaded");
			return;
		}
		
		switch(style) {
		case LeftTop:
			g.drawImage(image, 0, 0, parent());
			break;
		case RightBottom: 
			int x = this.getWidth() - image.getWidth(null);
			int y = this.getHeight() - image.getHeight(null);
			g.drawImage(image, x, y, parent());
			break;
		case Scaled:
			g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), parent());
			break;
		case Render:
			g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), parent());
			break;
		default:
			break;
		}
	}
	
	Component parent() {
		Container p = this.getParent();
		if(p == null)
			return this;
		else 
			return p;
	}
	
	
	@Override
	protected void paintComponent(Graphics g) {
		if(this.ownerDraw) {
			super.paintComponent(g);
		}
		paintImage(g);
	}

}
